<template>
  <div class="deposit-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="20" />
      </div>
      <h1 class="header-title">充值</h1>
    </div>
    
    <!-- 币种选择 -->
    <div class="currency-section">
      <div class="section-header">
        <h2 class="section-title">选择币种</h2>
        <div class="record-link" @click="goToTransactions">
          充值记录 <van-icon name="arrow" />
        </div>
      </div>
      <div class="currency-list">
        <div 
          v-for="item in currencies" 
          :key="item.name"
          :class="['currency-item', selectedCurrency === item.name ? 'selected' : '']"
          @click="selectCurrency(item)"
        >
          <div class="currency-icon" :style="{ backgroundColor: getCurrencyColor(item.name) }">
            {{ item.name.substring(0, 3) }}
          </div>
          <div class="currency-info">
            <span class="currency-name">{{ item.name }}</span>
          </div>
          <van-icon name="success" v-if="selectedCurrency === item.name" class="selected-icon" />
        </div>
      </div>
    </div>
    
    <!-- 网络选择 -->
    <div class="network-section" v-if="currentChains.length > 0">
      <h2 class="section-title">选择网络</h2>
      <div class="network-list">
        <div 
          v-for="chain in currentChains" 
          :key="chain.id"
          :class="['network-item', selectedChainId === chain.id ? 'selected' : '']"
          @click="selectChain(chain)"
        >
          <div class="network-icon">
            <van-image
              width="24"
              height="24"
              :src="chain.icon"
              fit="contain"
              :alt="chain.name"
            >
              <template #error>
                <div class="network-icon-fallback">{{ chain.name.substring(0, 2) }}</div>
              </template>
            </van-image>
          </div>
          <div class="network-info">
            <span class="network-name">{{ chain.name }}</span>
          </div>
          <van-icon name="success" v-if="selectedChainId === chain.id" class="selected-icon" />
        </div>
      </div>
    </div>
    
    <!-- 充值金额 -->
    <div class="amount-section">
      <h2 class="section-title">充值金额</h2>
      <div class="amount-input-container">
        <div class="amount-prefix">{{ selectedCurrency }}</div>
        <van-field
          v-model="amount"
          type="digit"
          placeholder="请输入充值金额"
          class="amount-input"
          :formatter="formatter"
        />
      </div>
      
      <div class="quick-amounts">
        <div 
          v-for="(quickAmount, index) in quickAmounts" 
          :key="index"
          class="quick-amount-item"
          @click="setAmount(quickAmount)"
        >
          {{ quickAmount }}
        </div>
      </div>
      
      <div class="amount-note">
        <van-icon name="info-o" />
        <span>最小充值金额: {{ minDepositAmount }} {{ selectedCurrency }}</span>
      </div>
    </div>
    
    <!-- 充值地址 -->
    <div class="address-section">
      <h2 class="section-title">充值地址</h2>
      <div class="address-row">
        <van-loading v-if="addressLoading" type="spinner" size="20px">加载中...</van-loading>
        <template v-else>
          <div class="address-text">
            <div class="address-value-container">
              <span class="address-value">{{ depositAddress }}</span>
              <van-button 
                size="mini" 
                type="primary" 
                icon="copy" 
                plain 
                class="copy-button"
                @click="copyAddress"
              >
                复制
              </van-button>
            </div>
          </div>
        </template>
      </div>
      
      <div class="confirm-section">
        <van-button 
          type="primary" 
          block 
          :disabled="!depositAddress || !amount" 
          @click="confirmDeposit"
        >
          确认充值
        </van-button>
      </div>
      
      <div class="address-note">
        <van-icon name="warning-o" class="warning-icon" />
        <div class="note-content">
          <p>请确保从正规渠道转入资产，且转入的区块链网络正确。</p>
          <p>充值到账时间取决于区块链网络确认时间，一般需要10-30分钟。</p>
        </div>
      </div>
    </div>
    
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showDialog } from 'vant'
import { getSupportedCurrencies, userDeposit,userDepositHash } from '@/api/cash'
import { getUserAddress } from '@/utils/auth/sessionManager'
import { 
  checkIfWalletInstalled, 
  switchNetwork, 
  transferByWalletType, 
  validateChainConfig 
} from '@/utils/wallet'

const router = useRouter()
const route = useRoute()

// 状态变量
const loading = ref(false)
const addressLoading = ref(false)

// 获取URL参数中的币种
const getInitialCurrency = () => {
  return route.query.currency || ''
}

const selectedCurrency = ref(getInitialCurrency())
const selectedChainId = ref(null)
const amount = ref('')
const minDepositAmount = ref(10) // 默认最小充值金额

// 币种列表
const currencies = ref([])
// 当前选中币种的链列表
const currentChains = ref([])

// 更新当前币种的链列表
const updateCurrentChains = (currencyName) => {
  const currency = currencies.value.find(c => c.name === currencyName)
  if (currency && currency.chains && Array.isArray(currency.chains)) {
    currentChains.value = currency.chains
    //console.log('当前币种链列表:', currentChains.value)
    
    // 如果有链，默认选择第一个
    if (currentChains.value.length > 0) {
      selectChain(currentChains.value[0])
    } else {
      selectedChainId.value = null
    }
  } else {
    currentChains.value = []
    selectedChainId.value = null
    //console.log('当前币种没有链列表')
  }
}

// 快速金额选择
const quickAmounts = ['100', '500', '1000', '5000', '10000']

// 加载币种列表
const loadCurrencies = async () => {
  loading.value = true
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  
  try {
    const res = await getSupportedCurrencies()
    if (res.code === 0 && res.data) {
      currencies.value = res.data
      //console.log('获取到的币种列表:', currencies.value)
      
      // 如果URL中有币种参数，则选择该币种
      const initialCurrency = getInitialCurrency()
      if (initialCurrency && currencies.value.some(c => c.name === initialCurrency)) {
        const currency = currencies.value.find(c => c.name === initialCurrency)
        selectCurrency(currency)
      } else if (currencies.value.length > 0) {
        // 否则选择第一个币种
        selectCurrency(currencies.value[0])
      }
    } else {
      showToast(res.message || '获取币种列表失败')
    }
  } catch (error) {
    //console.error('获取币种列表出错:', error)
    showToast('获取币种列表出错')
  } finally {
    loading.value = false
    closeToast()
  }
}


// 计算当前选择币种的充值地址
const depositAddress = computed(() => {
  if (!selectedChainId.value) return ''
  
  const chain = currentChains.value.find(c => c.id === selectedChainId.value)
  return chain ? chain.toAddress : ''
})

// 获取币种颜色
const getCurrencyColor = (name) => {
  const colors = {
    'HDFS': '#10b981',
    'USDT': '#3b82f6',
    'BTC': '#f59e0b',
    'ETH': '#8b5cf6'
  }
  
  return colors[name] || '#64748b'
}

// 计算当前选择币种的最小充值金额
const getMinDepositAmount = (currency) => {
  if (!currency) return 10
  
  // 如果币种有min字段，则使用该值
  if (currency.min !== undefined) {
    return currency.min
  }
  
  // 如果币种的链有min字段，则使用第一个链的min值
  if (currency.chains && currency.chains.length > 0) {
    const firstChain = currency.chains[0]
    if (firstChain.min !== undefined) {
      return firstChain.min
    }
  }
  
  // 默认返回10
  return 10
}

// 选择币种
const selectCurrency = (currency) => {
  if (selectedCurrency.value === currency.name) return // 避免重复选择同一币种
  
  //console.log('切换币种:', currency.name)
  selectedCurrency.value = currency.name
  
  // 更新当前币种的链列表
  updateCurrentChains(currency.name)
  
  // 更新最小充值金额
  minDepositAmount.value = getMinDepositAmount(currency)
}

// 选择链
const selectChain = (chain) => {
  if (selectedChainId.value === chain.id) return // 避免重复选择同一链
  
  //console.log('切换网络:', chain.name)
  selectedChainId.value = chain.id
  
  // 显示加载提示
  addressLoading.value = true
  
  // 模拟加载过程
  setTimeout(() => {
    addressLoading.value = false
  }, 500)
}

// 设置金额
const setAmount = (value) => {
  amount.value = value
}

// 格式化输入金额
const formatter = (value) => {
  // 限制小数点后两位
  if (value.includes('.')) {
    const parts = value.split('.')
    if (parts[1].length > 2) {
      return `${parts[0]}.${parts[1].substring(0, 2)}`
    }
  }
  return value
}

// 复制地址
const copyAddress = () => {
  if (!depositAddress.value) {
    showToast('暂无充值地址')
    return
  }
  
  navigator.clipboard.writeText(depositAddress.value)
    .then(() => {
      showToast('地址已复制')
    })
    .catch(() => {
      showToast('复制失败，请手动复制')
    })
}

// 确认充值
const confirmDeposit = () => {
  if (!amount.value) {
    showToast('请输入充值金额')
    return
  }
  
  if (!depositAddress.value) {
    showToast('请选择充值网络')
    return
  }
  
  // 检查是否满足最小充值金额要求
  const amt =  parseFloat(amount.value)
  if (amt < minDepositAmount.value) {
    showToast(`充值金额不能小于${minDepositAmount.value}`)
    return
  }
  
  // 获取当前选择的链信息
  const selectedChain = currentChains.value.find(c => c.id === selectedChainId.value)
  if (!selectedChain) {
    showToast('请选择充值网络')
    return
  }
  
  showDialog({
    title: '确认充值',
    message: `您确定要充值 ${amt} ${selectedCurrency.value} 吗？`,
    showCancelButton: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    showLoadingToast({
      message: '处理中...',
      forbidClick: true,
      duration: 0
    })
    
    // 获取当前用户地址
    const userAddress = getUserAddress()
    if (!userAddress) {
      closeToast()
      showToast('获取用户地址失败，请重新登录')
      return
    }
    
    // 调用充值接口
    userDeposit({
      icon: selectedCurrency.value,
      amount: amt+"",
      chainId: selectedChainId.value,
      address: userAddress // 添加用户地址参数
    }).then(res => {
      closeToast()
      
      if (res.code === 0) {
        // 保存订单号
        if (res.data && res.data.orderNo) {
          currentOrderNo.value = res.data.orderNo
          console.log('充值订单号:', currentOrderNo.value)
        } else {
          console.warn('未获取到订单号')
          currentOrderNo.value = ''
        }
        
        // 显示充值提示并询问是否立即转账
        showDialog({
          title: '充值申请成功',
          message: `充值申请已提交，是否立即使用钱包转账？`,
          showCancelButton: true,
          confirmButtonText: '立即转账',
          cancelButtonText: '稍后手动转账'
        }).then(() => {
          // 用户点击立即转账，唤起钱包
          initiateWalletTransfer(selectedChain, depositAddress.value, amt)
        }).catch(() => {
          // 用户选择稍后手动转账，显示地址信息
          showDialog({
            title: '充值提示',
            message: `请使用 ${selectedChain.name} 进行充值，充值地址为：${depositAddress.value}`,
            confirmButtonText: '我知道了'
          })
        })
       
         // 清空金额
        amount.value = ''
      } else {
        showToast(res.message || '充值申请失败')
      }
    }).catch(error => {
      closeToast()
      //console.error('充值申请失败:', error)
      showToast('充值申请失败，请稍后重试')
    })
  }).catch(() => {
    // 用户取消操作
  })
}


// 根据当前选择的链构造链配置
const buildChainConfig = (chain) => {
  if (!chain) return null
  
  // 将10进制链ID转换为16进制
  const chainIdHex = '0x' + parseInt(chain.id, 10).toString(16)
  
  // 构造链配置
  return {
    chainId: chainIdHex,
    chainName: chain.name,
    nativeCurrency: {
      name: chain.iconType,
      symbol: chain.iconType,
      decimals: chain.precision
    },
    rpcUrls: chain.url,
    blockExplorerUrls: [chain.explorerUrl || 'https://etherscan.io']
  }
}

// 存储当前订单号
const currentOrderNo = ref('')

// 唤起钱包转账
const initiateWalletTransfer = async (chain, toAddress, amount) => {
  try {
    // 检查是否安装了钱包
    if (!checkIfWalletInstalled()) {
      showToast('未检测到钱包插件，请安装MetaMask或TokenPocket')
      return
    }
    
    // 显示加载提示
    showLoadingToast({
      message: '连接钱包中...',
      forbidClick: true,
      duration: 0
    })
    
    // 获取链配置 - 使用当前选择的链数据构造配置
    const chainConfig = buildChainConfig(chain)
    if (!chainConfig) {
      closeToast()
      showToast(`无法构造链配置: ${chain.name}`)
      return
    }
    
    console.log('链配置:', chainConfig)
    
    // 验证并切换到正确的网络
    const validChainConfig = validateChainConfig(chainConfig)
    if (!validChainConfig) {
      closeToast()
      showToast('链配置无效')
      return
    }
    
    await switchNetwork(validChainConfig)
    
    // 确保金额是有效的数字
    const amountValue = parseFloat(amount)
    console.log('amountValue:', amountValue,amount)
    if (isNaN(amountValue) || amountValue <= 0) {
      closeToast()
      showToast('无效的转账金额')
      return
    }
    
    console.log('转账金额:', amountValue)
    
    // 准备转账参数
    const transferParams = {
      to: toAddress,
      amount: amountValue,
      // 如果是原生代币，tokenAddress为null
      tokenAddress: chain.contact || null,
      decimals: chain.precision || 18
    }
    
    closeToast()
    
    // 发起转账
    const txHash = await transferByWalletType(transferParams)
    
    // 转账成功
    showToast('转账请求已发送')
    
    // 如果有交易哈希，更新订单的交易哈希
    if (txHash && currentOrderNo.value) {
      console.log('交易哈希:', txHash)
      
      // 显示加载提示
      showLoadingToast({
        message: '更新交易哈希...',
        forbidClick: true,
        duration: 0
      })
      
      try {
        // 调用API更新订单的交易哈希
        const res = await userDepositHash({
          orderNo: currentOrderNo.value,
          txHash: txHash
        })
        
        closeToast()
        
        if (res.code === 0) {
          showToast('交易哈希已更新')
        } else {
          console.error('更新交易哈希失败:', res.message)
          showToast(res.message || '更新交易哈希失败')
        }
      } catch (error) {
        closeToast()
        console.error('更新交易哈希出错:', error)
        showToast('更新交易哈希出错，请联系客服')
      }
    }
    
  } catch (error) {
    closeToast()
    showToast(error.message || '转账失败')
    console.error('钱包转账错误:', error)
  }
}

// 导航方法
const goBack = () => {
  router.back()
}

const goToTransactions = () => {
  router.push(`/transactions?currency=${selectedCurrency.value}`)
}

// 初始化
onMounted(() => {
  loadCurrencies()
  
  // 如果有初始币种但还没有加载币种列表，需要监听币种列表加载完成后更新网络
  const initialCurrency = getInitialCurrency()
  if (initialCurrency && currencies.value.length === 0) {
    const checkCurrencies = setInterval(() => {
      if (currencies.value.length > 0) {
        clearInterval(checkCurrencies)
        const currency = currencies.value.find(c => c.name === initialCurrency)
        if (currency) {
          updateCurrentChains(initialCurrency)
        }
      }
    }, 100)
    
    // 设置超时，避免无限循环
    setTimeout(() => clearInterval(checkCurrencies), 5000)
  }
})
</script>

<style scoped>
.deposit-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 24px;
}

/* 顶部导航 */
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  cursor: pointer;
  color: #334155;
  background: transparent;
  border: none;
  padding: 0;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

/* 币种选择 */
.currency-section {
  background-color: #ffffff;
  padding: 16px;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #334155;
  margin-bottom: 0;
}

.record-link {
  font-size: 14px;
  color: #3b82f6;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.record-link .van-icon {
  font-size: 12px;
  margin-left: 2px;
}

.currency-list {
  display: flex;
  overflow-x: auto;
  gap: 12px;
  padding-bottom: 8px;
}

.currency-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  background-color: #f8fafc;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
  position: relative;
}

.currency-item:active {
  background-color: #f1f5f9;
}

.currency-item.selected {
  background-color: #eff6ff;
  border: 1px solid #3b82f6;
}

.currency-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 16px;
  font-weight: bold;
  color: white;
}

.currency-info {
  text-align: center;
}

.currency-name {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

.selected-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  color: #3b82f6;
  font-size: 16px;
  background-color: white;
  border-radius: 50%;
}

/* 网络选择 */
.network-section {
  background-color: #ffffff;
  padding: 16px;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.network-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.network-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  background-color: #f8fafc;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.network-item:active {
  background-color: #f1f5f9;
}

.network-item.selected {
  background-color: #eff6ff;
  border: 1px solid #3b82f6;
}

.network-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  background-color: #e2e8f0;
  overflow: hidden;
}

.network-icon-fallback {
  font-size: 14px;
  font-weight: bold;
  color: #64748b;
}

.network-info {
  flex: 1;
}

.network-name {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

/* 充值金额 */
.amount-section {
  background-color: #ffffff;
  padding: 16px;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.amount-input-container {
  display: flex;
  align-items: center;
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 4px 12px;
  margin-bottom: 12px;
}

.amount-prefix {
  font-size: 16px;
  font-weight: 500;
  color: #334155;
  margin-right: 8px;
}

.amount-input {
  flex: 1;
  background-color: transparent;
}

.amount-input :deep(.van-field__control) {
  font-size: 18px;
  font-weight: 500;
  color: #1e293b;
}

.quick-amounts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.quick-amount-item {
  padding: 8px 12px;
  background-color: #f8fafc;
  border-radius: 6px;
  font-size: 14px;
  color: #334155;
  cursor: pointer;
  transition: background-color 0.2s;
}

.quick-amount-item:active {
  background-color: #f1f5f9;
}

.amount-note {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #64748b;
}

.amount-note .van-icon {
  margin-right: 6px;
  color: #3b82f6;
}

/* 充值地址 */
.address-section {
  background-color: #ffffff;
  padding: 16px;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.address-row {
  display: flex;
  align-items: center;
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
}

.address-text {
  width: 100%;
}

.address-value-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #ffffff;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px dashed #cbd5e1;
}

.address-value {
  font-size: 14px;
  color: #334155;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-button {
  color: #3b82f6;
  border-color: #3b82f6;
  margin-left: 8px;
  flex-shrink: 0;
}

.confirm-section {
  margin-bottom: 16px;
}

.address-note {
  display: flex;
  padding: 12px;
  background-color: #fffbeb;
  border-radius: 8px;
  border: 1px solid #fef3c7;
}

.warning-icon {
  color: #f59e0b;
  font-size: 18px;
  margin-right: 8px;
  flex-shrink: 0;
  margin-top: 2px;
}

.note-content {
  font-size: 14px;
  color: #92400e;
}

.note-content p {
  margin: 0 0 6px;
}

.note-content p:last-child {
  margin-bottom: 0;
}

</style>